package org.hishenframework.core.security;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;

public class SecurityService {

	private JdbcTemplate jdbcTemplate;

	@Resource
	public void setDataSource(DataSource dataSource) {
		jdbcTemplate = new JdbcTemplate(dataSource);
	}

	// public Map<String, List<ConfigAttribute>> getAllAccessToSource(){
	// String sql = "SELECT * FROM t_";
	//
	// jdbcTemplate.queryForList(sql);
	//
	// return null;
	// }

	public List<Map<String, Object>> getAllResources() {
		String sql = "SELECT * FROM t_system_resource";
		return jdbcTemplate.queryForList(sql);
	}

	public List<Map<String, Object>> getAllRoles() {
		String sql = "SELECT * FROM t_system_role";
		return jdbcTemplate.queryForList(sql);
	}

	public List<Map<String, Object>> getAllUsers() {
		String sql = "SELECT * FROM t_system_user";
		return jdbcTemplate.queryForList(sql);
	}

	public List<Map<String, Object>> getUserRole() {
		String sql = "SELECT * FROM t_system_user_role";
		return jdbcTemplate.queryForList(sql);
	}

	public List<Map<String, Object>> getRoleResource() {
		String sql = "SELECT * FROM t_system_role_resource";
		return jdbcTemplate.queryForList(sql);
	}

	public List<Map<String, Object>> getRolesByResource() {
		String sql = "SELECT rr.resource_id, r.role FROM t_system_role_resource rr LEFT JOIN t_system_role r ON rr.role_id = r.id";
		return jdbcTemplate.queryForList(sql);
	}

	public Map<String, Object> getUserByUsername(String username) {
		String sql = "SELECT username, password, enabled FROM t_system_user WHERE username = ?";
		List<Map<String, Object>> list = jdbcTemplate.queryForList(sql,
				username);
		return list.size() == 0 ? null : list.get(0);
	}

	public List<Map<String, Object>> getRolesByUsername(String username) {
		String sql = "SELECT u.username, r.role FROM t_system_user u JOIN t_system_user_role ur ON u.id = ur.user_id JOIN t_system_role r ON r.id = ur.role_id WHERE u.username = ?";
		return jdbcTemplate.queryForList(sql, username);
	}
}
